﻿using System;
using System.Threading;

namespace MultiViewer.Network
{
    public class HandlerResult<T> 
    {
        private AutoResetEvent set = new AutoResetEvent(false);
        private T success;
        private Exception fault;

        public void SetSuccess(T v)
        {
            success = v;
            set.Set();
        }

        public void SetFailure(Exception exc)
        {
            fault = exc;
            set.Set();
        }

        public bool IsSuccess
        {
            get { return fault == null; }
        }

        public T Value
        {
            get {
                if (fault != null)
                    throw new InvalidOperationException("Cannot get successful result for fault");
                return success; 
            }
        }

        public Exception Fault
        {
            get {
                if (fault == null)
                    throw new InvalidOperationException("Cannot get fault for successful result");
                return fault; 
            }
        }

        public void WaitForResult()
        {
            set.WaitOne();
        }
    }
}